import cloudAdapter from "@/cloudAdapter/index.js";
import { ErrorLogger } from "./Logger";
import Query from "./query.js";
import { unionBy, differenceBy } from "lodash-es";
import searchSort from "@/utils/searchSort";
const stateTree = {
    state: () => ({
        PublicSnippets: new Query({
            request: cloudAdapter.querySnippets.bind(cloudAdapter),
        }),
        SearchResult: [],
    }),
    mutations: {
        changeSearchResult(state, result) {
            // 用户点击 搜索 按钮
            console.info("搜索结果: ", result);
            state.SearchResult = result || [];
        },
        updateSearchResult(state, updateArray) {
            state.SearchResult = unionBy(
                updateArray,
                state.SearchResult,
                "_id"
            );
        },
        deleteSearchSnippet(state, removeArray) {
            state.SearchResult = differenceBy(
                state.SearchResult,
                removeArray,
                "_id"
            );
        },
    },
    actions: {
        async PutSnippet(_, snippet) {
            console.log(snippet);
            return await cloudAdapter
                .PutSnippet({ ...snippet, author: window.UserInfo.uid })
                .then(({ id }) => {
                    return { _id: id, ...snippet };
                })
                .catch(ErrorLogger);
        },
        RefreshSnippet({ commit }, id) {
            return cloudAdapter.refreshSnippet(id).then((res) => {
                commit("updateSearchResult", res);
                return res;
            });
        },
        DeleteSnippet({ commit }, id) {
            return cloudAdapter
                .deleteSnippet(id)
                .then(() => {
                    commit("deleteSearchSnippet", [{ _id: id }]);
                })
                .catch(ErrorLogger);
        },
        async searchSnippets({ commit }, template) {
            const result = await cloudAdapter
                .searchSnippets(template)
                .then((res) => {
                    return searchSort(
                        res,
                        [template.text],
                        ["title", "description", "body"]
                    );
                })
                .catch(ErrorLogger);
            commit("changeSearchResult", result);
        },
    },
};

export default stateTree;
